/* eslint-disable import/no-extraneous-dependencies */
const execa = require('execa');
const path = require('path');
const getRepositoryModule = require('../utils/getRepositoryModule');
const selectModule = require('../utils/selectModule');

const defaultTemplate = path.resolve(
  __dirname,
  '../../public/default/index.html',
);
// const HelloWorldPlugin = require("../plugins/HelloWorldPlugin");
// const ReplaceTextWebpackPlugin = require("../plugins/ReplaceTextWebpackPlugin");

function formatPages(pages) {
  return pages.reduce((res, { name, entry, filename }) => ({
    ...res,
    [name]: {
      template: defaultTemplate,
      entry,
      filename,
    },
  }), []);
}

module.exports = (api, options) => {
  if (process.env.___devPages) {
    options.pages = formatPages(JSON.parse(process.env.___devPages));

    // api.chainWebpack((webpackConfig) => {
    //   webpackConfig.plugin("ReplaceTextWebpackPlugin").use(ReplaceTextWebpackPlugin, []);
    // });
    // api.chainWebpack((webpackConfig) => {
    //   webpackConfig
    //     .plugin("HelloWorldPlugin")
    //     .use(HelloWorldPlugin, [
    //       { ignoreLoaders: ["postcss-loader"], warnings: true, errors: false },
    //     ]);
    // });
  } else {
    api.registerCommand('muti-dev', async (args) => {
      const { pluginOptions: { 'muti-dev': { sourceSrc, debug } } = {} } = options;

      const modules = await selectModule(
        getRepositoryModule(sourceSrc),
        args._,
      );
      console.log(
        '🚀 ~ file: index.js ~ line 16 ~ api.registerCommand ~ modules',
        modules,
      );

      execa('vue-cli-service', ['serve'], {
        stdio: 'inherit',
        env: {
          ___devPages: JSON.stringify(modules),
        },
      });
    });
  }
};

module.exports.defaultModes = {
  'muti-dev': 'development',
};
